﻿using AlarmClock.BLL;
using Model;
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using static AlarmClock.BLL.Service;

namespace AlarmClock.UI
{
    public partial class FrmAlarmClock : Form
    {
        /// <summary>
        /// 回调委托
        /// </summary>
        public ChangeClockHandler ChangeClock { get; set; }

        /// <summary>
        /// 闹钟服务 BLL层
        /// </summary>
        private ClockBLL clockBLL = new ClockBLL();

        private Clock curAlarmClock; //传入闹钟

        private PPNAudio myNAudio; //铃声播放器

        private FrmMask frmMask;//遮罩窗体

        private string weather => BaiduWeatherWebApi.AllWeatherInfo?.result?.now?.text;//天气
        private bool alarmingShowWeather => clockBLL.ReadAllClockConfig().alarmingShowWeather;//闹钟时显示本地天气

        private Timer timer;//窗体震动

        /// <summary>
        /// 无参构造函数
        /// </summary>
        public FrmAlarmClock() { }

        /// <summary>
        /// 有参构造函数 播放【闹铃】
        /// </summary>
        /// <param name="clock">闹钟信息</param>
        /// <param name="order">指令</param>
        public FrmAlarmClock(Clock clock, string order)
        {
            InitializeComponent();

            Service.SetControlTransparent(this.title, this);
            Service.SetControlTransparent(this.Things, this);

            if (clock == null) return;

            //加个背景
            frmMask = new FrmMask();
            frmMask.Show();

            this.curAlarmClock = clock;
            this.Name = order;

            this.Things.Text = curAlarmClock.clockInfo.things;
            if (clock.clockInfo.nextInterval == "无")
            {
                this.Splits.Panel1Collapsed = true;//收起稍后提醒按钮           
            }

            //天气GIF
            string gifPath = Service.GetWeatherGIFPath(weather, alarmingShowWeather);
            pictureBoxForWeather.ImageLocation = gifPath;
            pictureBoxForWeather.Load();
            //音乐
            string musicPath = Service.GetMusicPath(this.curAlarmClock.clockInfo.music);
            myNAudio = new PPNAudio(musicPath);
            //音量：设置音量需要别名
            float volume = Service.GetAlarmVolume(this.curAlarmClock.clockInfo.musicVolume);
            myNAudio.SetVolume(volume);
            myNAudio.PlayRepeat();

            //响铃时震动
            if (clock.clockInfo.musicPlus == "1")
            {
                timer = new Timer();
                timer.Interval = 30;
                timer.Tick += (s, e) =>
                {
                    int left = this.Left;
                    int top = this.Top;
                    for (int i = 0; i < 20; i++)
                    {
                        this.Left += i % 2 == 0 ? 10 : -10;
                        this.Top += i % 2 == 0 ? 10 : -10;
                    }
                    this.Left = left;
                    this.Top = top;
                };
                timer.Start();
            }

            //记录历史
            string his_Path = Path.Combine(Application.StartupPath, "history.rec");
            FileStream fs = new FileStream(his_Path, FileMode.Append);
            StreamWriter streamWriter = new StreamWriter(fs);
            streamWriter.WriteLine(clock.ToString());
            streamWriter.Close();
            fs.Close();
        }


        #region GIF闹钟图播放

        /// <summary>
        /// 关闭GIF【闹铃】动画
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void afterAlarmAgain_Click(object sender, EventArgs e)
        {
            changeClock(curAlarmClock, "稍后提醒");
            frmMask.Close();
        }

        #endregion

        #region 【闹钟】铃声播放、关闭       

        /// <summary>
        /// 关闭【闹钟】
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Close_Click(object sender, EventArgs e)
        {
            changeClock(curAlarmClock,"关闭闹钟");
            frmMask.Close();
        }

        /// <summary>
        /// 修改闹钟信息
        /// </summary>
        /// <param name="clock"></param>
        /// <param name="order"></param>
        private void changeClock(Clock clock,string order)
        {
            if (order=="关闭闹钟")
            {
                string next = curAlarmClock.clockInfo.repeat.Trim();
                var dtTime = DateTime.Parse(curAlarmClock.clockInfo.time.Trim());
                switch (next)
                {
                    case "每天":
                        dtTime = dtTime.AddDays(1);
                        break;
                    case "每周":
                        dtTime = dtTime.AddDays(7);
                        break;
                    case "每月":
                        dtTime = dtTime.AddMonths(1);
                        break;
                    case "自定义":
                        break;
                    case "法定工作日（自动跳过节假日）":
                        break;
                    case "不重复":
                        curAlarmClock.clockInfo.isActive = "0";//关闭
                        break;
                    default:
                        int add_Number = -1;
                        if (next.Any(char.IsDigit) && next.Length >= 3)
                        {
                            _ = int.TryParse(next.Substring(1, next.Length - 2), out add_Number);
                        }
                        if (add_Number != -1)
                        {
                            for (int i = 0; i < add_Number; i++)
                            {
                                if (next.Contains("天"))
                                {
                                    dtTime = dtTime.AddDays(1);
                                }
                                else if (next.Contains("周"))
                                {
                                    dtTime = dtTime.AddDays(7);
                                }
                                else if (next.Contains("月"))
                                {
                                    dtTime = dtTime.AddMonths(1);
                                }
                            }
                            break;
                        }
                        break;
                }

                curAlarmClock.clockInfo.time = dtTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else if(order=="稍后提醒")
            {
                string next = curAlarmClock.clockInfo.nextInterval;
                if (next == "5分钟") 
                    curAlarmClock.clockInfo.time = DateTime.Now.AddMinutes(5).ToString("yyyy-MM-dd HH:mm:ss");
                else if(next=="10分钟")
                    curAlarmClock.clockInfo.time = DateTime.Now.AddMinutes(10).ToString("yyyy-MM-dd HH:mm:ss");
                else if (next == "15分钟")
                    curAlarmClock.clockInfo.time = DateTime.Now.AddMinutes(15).ToString("yyyy-MM-dd HH:mm:ss");
            }

            //1.更新当前闹钟信息
            clockBLL.UpdateClock(curAlarmClock);

            //2.委托更新主界面UI
            ChangeClock?.Invoke(clock, Constant.CLOCK_UPDATE);


            //3.关闭铃声、闹钟UI
            myNAudio?.Stop();
            this.Close();
        }

        #endregion

        #region 窗体渐入渐出效果

        private void FrmAlarmClock_FormClosing(object sender, FormClosingEventArgs e)
        {
            PPWin32.AnimateWindow(this.Handle, 1000, PPWin32.AW_BLEND | PPWin32.AW_HIDE);
        }

        private void FrmAlarmClock_Load(object sender, EventArgs e)
        {
            PPWin32.AnimateWindow(this.Handle, 1000, PPWin32.AW_SLIDE | PPWin32.AW_ACTIVATE | PPWin32.AW_VER_NEGATIVE);
        }

        #endregion
    }
}
